<template>
  <BackTab>
    <template v-slot:center>用户信息管理中心___</template>
    <template v-slot:icon
      ><el-icon><UserFilled /></el-icon
    ></template>
    <template v-slot:list>用户列表</template>
  </BackTab>

  <el-card class="box-card">
    <div class="common-layout">
      <el-container>
        <el-header>
          <div class="search">
            <div class="name">用户名:</div>
            <el-input
              v-model="input"
              placeholder="输入搜索姓名"
              :suffix-icon="Search"
            />
            <el-button type="primary" class="seaBtn" @click="searchUser"
              >搜索</el-button
            >
            <el-button type="primary" @click="getUser">全部用户</el-button>
          </div>
          <div class="btnBox">
            <el-button type="primary" @click="addUser">添加用户</el-button>
          </div>
        </el-header>
        <el-main>
          <el-table :data="tableData" stripe border style="width: 100%">
            <el-table-column type="index" label="~" />
            <el-table-column prop="userName" label="姓名" width="150" />
            <el-table-column prop="userSex" label="性别" width="100" />
            <el-table-column prop="birthday" label="出生日期">
              <template #default="scope">
                {{ utils.ymd(scope.row.birthday) }}
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="address" label="居住地" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="info"
                  @click="detailsUser(scope.row.id)"
                  >详情</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="editUser(scope.row.id)"
                  >修改</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteUserOne(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </div>
  </el-card>

  <!-- 修改 -->
  <el-dialog v-model="editVisible" title="用户信息" width="30%" center>
    <el-form :model="singerUser" :rules="registRules" ref="registeRuleFormRef" label-width="120px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="singerUser.userName" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="singerUser.phone" />
      </el-form-item>
      <el-form-item label="居住地" prop="address">
        <el-input v-model="singerUser.address" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate(registeRuleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加 -->
  <el-dialog v-model="addVisible" title="添加用户" width="30%" center>
    <el-form :model="regisForm" :rules="registRules" ref="registeRuleFormRef">
      <el-form-item prop="userName">
        <el-input v-model="regisForm.userName" placeholder="用户名" />
      </el-form-item>
      <el-form-item prop="userPass">
        <el-input
          v-model="regisForm.userPass"
          placeholder="密码"
          type="password"
        />
      </el-form-item>
      <el-form-item prop="userSex">
        <el-radio-group v-model="regisForm.userSex">
          <el-radio label="男" />
          <el-radio label="女" />
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="birthday">
        <el-date-picker
          v-model="regisForm.birthday"
          type="date"
          placeholder="请选择出生日期"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="phone">
        <el-input v-model="regisForm.phone" placeholder="手机号" />
      </el-form-item>
      <el-form-item prop="address">
        <el-input v-model="regisForm.address" placeholder="居住地址" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="subRegiste(registeRuleFormRef)"
          >注册</el-button
        >
        <el-button @click="resetForm(registeRuleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 详情 -->
  <el-dialog
    v-model="deltailVisible"
    title="用户详情"
    class="detail"
    width="30%"
  >
    <div class="detailInfos">
      <div class="top">
        <img class="img" :src="singerUser.avater" alt="" />
      </div>
      <div class="bottom">
        <div class="item">
          <div class="label">姓名：</div>
          <div class="data">{{ singerUser.userName }}</div>
        </div>
        <div class="item">
          <div class="label">性别：</div>
          <div class="data">{{ singerUser.userSex }}</div>
        </div>
        <div class="item">
          <div class="label">年龄：</div>
          <div class="data">{{ age }}</div>
        </div>
        <div class="item">
          <div class="label">手机号：</div>
          <div class="data">{{ singerUser.phone }}</div>
        </div>
        <div class="item">
          <div class="label">居住地：</div>
          <div class="data">{{ singerUser.address }}</div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deltailVisible = false" type="primary"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import BackTab from "@/components/common/tabbar/BackTab.vue";
import { Search } from "@element-plus/icons-vue";
import { getCurrentInstance, onMounted, ref } from "vue";
import {
  getUserList,
  getSearchUser,
  getOneUser,
  deleteUser,
} from "@/server/user";
import utils from "@/utils/utils";
import { useRegist } from "@/hooks/loginForm/useRegist";
import { ElMessage, ElMessageBox, type FormInstance } from "element-plus";
const { registeRuleFormRef, registRules, regisForm, resetForm } = useRegist();
const { proxy }: any = getCurrentInstance();
// 搜索框
const input = ref("");
// 表格信息
const tableData = ref<any>([]);
// 添加
const addVisible = ref(false);
// 详情
const deltailVisible = ref(false);
// 修改
const editVisible = ref(false);
// 单个用户信息
const singerUser = ref<any>([]);
const age = ref<any>(0);
// 挂载页面执行函数
onMounted(async () => {
  await getUser();
});

//获取全部用户
const getUser = () => {
  getUserList().then((res: any) => {
    tableData.value = res.data.filter((item: any) => item.role == "user");
    input.value = "";
  });
};
//根据名字搜索用户
const searchUser = () => {
  if (input.value.trim() == "") return (input.value = "");
  getSearchUser(input.value).then((res: any) => {
    tableData.value = res.data.filter((item: any) => item.role == "user");
  });
};
//添加用户
const addUser = () => {
  addVisible.value = true;
};
//注册按钮
const subRegiste = async (regist: FormInstance | undefined) => {
  if (!regist) return;
  await regist.validate((valid) => {
    if (!valid) return;
    proxy.$http
      .post("/user/register", {
        userName: regisForm.userName,
        userPass: regisForm.userPass,
        userSex: regisForm.userSex,
        birthday: regisForm.birthday,
        phone: regisForm.phone,
        address: regisForm.address,
        avater: regisForm.avater,
      })
      .then(async (res: any) => {
        ElMessage.success(res.message);
        addVisible.value = false;
        await getUser();
      })
      .catch((err: any) => {
        ElMessage.error(err.response.data.message);
      });
  });
};

// 获取单个用户信息
function getOneUserInfos(id: number) {
  getOneUser(id).then((res: any) => {
    singerUser.value = res;
    age.value = utils.fillAge(JSON.stringify(res.birthday));
  });
}
//查看详情
const detailsUser = (id: number) => {
  deltailVisible.value = true;
  getOneUserInfos(id);
};
// 修改信息
const editUser = (id: number) => {
  editVisible.value = true;
  getOneUserInfos(id);
};
//修改提交按钮
const submitUpdate = async (updateInfo: FormInstance | undefined) => {
  if (!updateInfo) return;
  await updateInfo.validate((valid) => {
    if (!valid) return
    proxy.$http
      .post("/user/upinfos/" + singerUser.value.id, {
        userName: singerUser.value.userName,
        phone: singerUser.value.phone,
        address: singerUser.value.address,
      })
      .then(async (res: any) => {
        ElMessageBox.alert("你的信息保存成功", {
          confirmButtonText: "OK",
          callback: () => {
            ElMessage({
              type: "success",
              message: "提交成功",
            });
          },
        });
        editVisible.value = false
        await getUser()
        window.sessionStorage.setItem("Infos", JSON.stringify(res.data));
      });
  });
};
// 删除用户
const deleteUserOne = (id: number) => {
  ElMessageBox.confirm("是否删除该用户", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteUser(id).then(async (res: any) => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        await getUser();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败,该用户关联其他失联人",
      });
    });
};
</script>

<style scoped lang="less">
.common-layout {
  padding: 0;
  .el-container {
    .el-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // background-color: pink;
      border: 1px solid #ebeef5;
      padding: 10px;
      .search {
        display: flex;
        align-items: center;
        .name {
          width: 100px;
          font-weight: bolder;
        }
        .seaBtn {
          margin-left: 5px;
        }
      }
    }
    .el-main {
      padding: 0;
    }
  }
}
.detail {
  .detailInfos {
    display: flex;
    flex-direction: column;
    .top {
      width: 100px;
      height: 120px;
      .img {
        width: 100%;
        height: 100%;
      }
    }
    .bottom {
      margin-top: 15px;
      .item {
        display: flex;
        margin-bottom: 8px;
        .label {
          font-weight: bolder;
          padding-right: 8px;
        }
      }
    }
  }
}
</style>
